<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 * 商品属性类
 * 
 * @author  : $Author: spike $
 * @date    : $Date: 2014-03-03 09:31:20 +0800 (一, 2014-03-03) $
 * @version : $Id: attr_model.php 39 2014-03-03 01:31:20Z spike $
 * @rev     : $Revision: 39 $
 */
class Attr_model extends CI_Model
{
    public function __construct()
    {
        parent::__construct();

    }

    // --------------------------------------------------------------------
    
    /**
     * 验证属性,属性值的名称
     * 
     * @param  [string] 
     * @return [bool]
     */
    public function val_attr_name($val)
    {
        if( ! preg_match('/^[a-z|A-Z|\d|\x7f-\xff]{1,20}$/', $val) )
        {
            $this->set_error("属性名称只能包含中英文或数字, 1~20位。");
            return FALSE;
        }
        return TRUE;
    }

    // --------------------------------------------------------------------
    
    /**
     * [分页浏览]
     * @param  [array]  $params  [条件]
     * @param  [int]    $page    [当前页]
     * @param  [int]    $size    [页数，只允许app_config中"pagesize"的值]
     * @param  [string] $orderby [排序]
     * @return [array]
     */
    public function browse_attr_group($params, $page = NULL, $size = NULL, $orderby = '`attr_group_id` DESC')
    {
        $where = array(
            'is_delete' => UNDELETED,
        );
        $where_in = array();

        if( ! empty($params['name']) )
        {
            $where['`name` LIKE'] = "%".xss_clean(trim($params['name']))."%";
        }

        if( ! empty($params['status']) )
        {
            $attr_group_status = $this->config->item('attr_group_status');
            if( $attr_group_status["{$params['status']}"] )
                $where['status'] = $params['status'];
        }
      
        if( ! empty($params['create_time_start']) && strtotime($params['create_time_start']) )
        {
            $where['`create_time` >'] = $params['create_time_start'];
        }

        if( ! empty($params['create_time_end']) && strtotime($params['create_time_end']) )
        {
            $where['`create_time` <'] = $params['create_time_end'];
        }

        if( ! empty($params['update_time_start']) && strtotime($params['update_time_start']) )
        {
            $where['`update_time` >'] = $params['update_time_start'];
        }

        if( ! empty($params['update_time_end']) && strtotime($params['update_time_end']) )
        {
            $where['`update_time` <'] = $params['update_time_end'];
        }
        
        $pagesize = $this->config->item('pagesize');
        $size     = isset($pagesize[$size]) ? $size : 10;
        $offset   = intval(($page-1)*$size) > 0 ? intval(($page-1)*$size) : 0;
        $total    = 0;

        $this->load->dao('Attr_group_dao');
        $data = $this->Attr_group_dao->get_in(
            NULL,
            $where, 
            '*', 
            $orderby, 
            $size, 
            $offset, 
            TRUE, 
            $total
        );
        return array(
            'size' => $size,
            'data' => $data,
            'total'=> $total,
        );
    }

    // --------------------------------------------------------------------
        
    /**
     * [添加属性模版]
     * @param   [array]       $params
     * @return  [int/false]
     */
    public function add_attr_group($params)
    {
        $params = array(
            'name' => xss_clean(trim($params['name'])),
        );

        /* 校验名称开始 */
        if( ! validate_length($params['name'], 1, 20) )
        {
            $this->set_error("新增属性模版失败：模版名称最少1个字最多20个字。[{$params['name']}]");
            return FALSE;
        }
        $this->load->dao('Attr_group_dao');
        $count = $this->Attr_group_dao->count(array(
            'name'      => $params['name'],
            'is_delete' => UNDELETED,
        ));
        if( $count > 0 )
        {
            $this->set_error("新增属性模版失败：模版名称已存在。[{$params['name']}]");
            return FALSE;
        }
        $attr_group['name'] = $params['name'];
        /* 校验名称结束 */

        /* 写入属性方案开始 */
        $attr_group['status']       = ATTR_GROUP_STATUS_ON;
        $attr_group['is_delete']    = UNDELETED;
        $attr_group['create_admin'] = login_info('admin_id');
        $attr_group['create_time']  = now_str();

        $this->load->dao('Attr_group_dao');
        if( ! $attr_group_id = $this->Attr_group_dao->insert($attr_group))
        {
            $this->set_error("新增属性模版失败：无法写入数据库。");
            return FALSE;
        }
        /* 写入属性方案结束 */

        return $attr_group_id;
    }

    /**
     * [添加属性]
     * @param   [array]       $params
     * @return  [int/false]
     */
    public function add_attr($attr_group_id, $params)
    {
        if( ! validate($attr_group_id, 'ATTR_GROUP_ID') )
        {
            $this->set_error("新增属性失败：属性模版ID不正确。[{$attr_group_id}]");
            return FALSE;
        }
        $params = array(
            'name' => xss_clean(trim($params['name'])),
        );

        /* 校验attr_group_id开始 */
        $this->load->dao('Attr_group_dao');
        if( ! $attr_group = $this->Attr_group_dao->get_one(array(
            'attr_group_id' => $attr_group_id,
            'is_delete'     => UNDELETED,
        )))
        {
            $this->set_error("新增属性失败：指定的属性模版不存在。[{$attr_group_id}]");
            return FALSE;
        }

        if( $attr_group['status'] != ATTR_GROUP_STATUS_ON )
        {
            $this->set_error("新增属性失败：指定的属性模版没有开启。[{$attr_group_id}]");
            return FALSE;
        }
        $attr['attr_group_id'] = $attr_group_id;
        /* 校验attr_group_id结束 */

        /* 校验名称开始 */
        if( ! $this->val_attr_name($params['name']) )
        {
            return FALSE;
        }
        $this->load->dao('Attr_dao');
        $count = $this->Attr_dao->count(array(
            'attr_group_id' => $attr_group_id,
            'name'          => $params['name'],
            'is_delete'     => UNDELETED,
        ));
        if( $count > 0 )
        {
            $this->set_error("新增属性失败：属性名称已存在。[{$params['name']}]");
            return FALSE;
        }
        $attr['name'] = $params['name'];
        /* 校验名称结束 */

        /* 写入属性方案开始 */
        $attr['status']       = ATTR_STATUS_ON;
        $attr['sort']         = 255;
        $attr['is_delete']    = UNDELETED;
        $attr['create_admin'] = login_info('admin_id');
        $attr['create_time']  = now_str();

        $this->load->dao('Attr_dao');
        if( ! $attr_id = $this->Attr_dao->insert($attr))
        {
            $this->set_error("新增属性失败：无法写入数据库。");
            return FALSE;
        }
        /* 写入属性方案结束 */

        return $attr_id;
    }

    /**
     * [添加属性值]
     * @param   [array]       $params
     * @return  [int/false]
     */
    public function add_attr_value($attr_id, $params)
    {
        if( ! validate($attr_id, 'ATTR_ID') )
        {
            $this->set_error("新增属性值失败：属性ID不正确。[{$attr_id}]");
            return FALSE;
        }
        $params = array(
            'name' => xss_clean(trim($params['name'])),
        );

        /* 校验attr_id开始 */
        $this->load->dao('Attr_dao');
        if( ! $attr = $this->Attr_dao->get_one(array(
            'attr_id'   => $attr_id,
            'is_delete' => UNDELETED,
        )))
        {
            $this->set_error("新增属性值失败：指定的属性ID不存在。[{$attr_id}]");
            return FALSE;
        }

        if( $attr['status'] != ATTR_STATUS_ON )
        {
            $this->set_error("新增属性值失败：指定的属性没有开启。[{$attr_id}]");
            return FALSE;
        }
        $attr_value['attr_id'] = $attr_id;
        /* 校验attr_结束 */

        /* 校验名称开始 */
        if( ! $this->val_attr_name($params['name']) )
        {
            return FALSE;
        }

        $this->load->dao('Attr_value_dao');
        $count = $this->Attr_value_dao->count(array(
            'attr_id'   => $attr_id,
            'name'      => $params['name'],
            'is_delete' => UNDELETED,
        ));
        if( $count > 0 )
        {
            $this->set_error("新增属性值失败：属性值名称已存在。[{$params['name']}]");
            return FALSE;
        }
        $attr_value['name'] = $params['name'];
        /* 校验名称结束 */

        /* 写入属性值开始 */
        $attr_value['status']       = ATTR_VALUE_STATUS_ON;
        $attr_value['sort']         = 255;
        $attr_value['is_delete']    = UNDELETED;
        $attr_value['create_admin'] = login_info('admin_id');
        $attr_value['create_time']  = now_str();

        $this->load->dao('Attr_value_dao');
        if( ! $attr_value_id = $this->Attr_value_dao->insert($attr_value))
        {
            $this->set_error("新增属性值失败：无法写入数据库。");
            return FALSE;
        }
        /* 写入属性值结束 */

        return $attr_value_id;
    }

    // --------------------------------------------------------------------

    /**
     * [获得一个属性模版]
     * @param  [string]     $id
     * @param  [bool]       $enable        [是否排除"关闭状态"]
     * @param  [bool]       $with_attr     [是否包含属性值的信息]
     * @return [array/false]
     */
    public function get_attr_group($id, $enable = TRUE, $with_attr = FALSE)
    {
        if( ! validate($id, 'ATTR_GROUP_ID') )
        {
            $this->set_error("获取属性模版失败：ID不正确。[{$id}]");
            return FALSE;
        }
        
        $where = array(
            'attr_group_id' => $id,
            'is_delete'     => UNDELETED,
        );
        if($enable === TRUE)
        {
            $where['status'] = ATTR_GROUP_STATUS_ON;
        }

        $this->load->dao('Attr_group_dao');
        $attr_group = $this->Attr_group_dao->get_one($where);
        if( ! $attr_group)
        {
            $this->set_error("获取属性模版失败：无法找到属性模版。[{$id}]。");
            return FALSE;
        }

        if( $with_attr === TRUE )
        {
            $where = array(
                'attr_group_id' => $id,
                'is_delete'     => UNDELETED,
            );
            if($enable === TRUE)
            {
                $where['status'] = ATTR_STATUS_ON;
            };

            $this->load->dao('Attr_dao');
            $attr_group['children'] = $this->Attr_dao->get(
                $where, 
                array(
                    'attr_id','name','sort','status'
                ), 
                '`sort` ASC, `attr_id` ASC'
            );
            if( $attr_group['children'] )
            {
                $attr_value_ids = array_pick($attr_group['children'], 'attr_id', TRUE);

                $where = array(
                    'is_delete' => UNDELETED,
                );
                if($enable === TRUE)
                {
                    $where['status'] = ATTR_VALUE_STATUS_ON;
                };

                $this->load->dao('Attr_value_dao');
                $attr_values = $this->Attr_value_dao->get_in(
                    array('attr_id'=>$attr_value_ids), 
                    $where, 
                    array(
                        'attr_id','attr_value_id','name','sort','status'
                    ), 
                    '`attr_id` ASC, `sort` ASC, `attr_value_id` ASC'
                );

                array_change_key($attr_group['children'], 'attr_id');
                foreach ($attr_values as $av) 
                {
                    $attr_id = $av['attr_id'];
                    if( isset($attr_group['children'][$attr_id]) )
                    {
                        $attr_group['children'][$attr_id]['children'][] = $av;
                    }
                }
            }

        }
        return $attr_group;
    }

    /**
     * [获得一个属性模版]
     * @param  [string]     $category_id
     * @param  [bool]       $enable             [是否排除"关闭状态"]
     * @param  [bool]       $with_attr_value    [是否包含属性值的信息]
     * @return [array/false]
     */
    public function get_attr_by_category($category_id, $enable = TRUE, $with_attr_value = FALSE)
    {
        if( ! validate($category_id, 'CATEGORY_ID') )
        {
            $this->set_error("获取分类属性失败：ID不正确。[{$id}]");
            return FALSE;
        }
        
        /* 获取分类开始 */
        $where = array(
            'category_id' => $category_id,
            'is_delete'   => UNDELETED,
        );
        if($enable === TRUE)
        {
            $where['status'] = CATEGORY_STATUS_ON;
        }

        $this->load->dao('Category_dao');
        $category = $this->Category_dao->get_one($where);
        if( ! $category)
        {
            $this->set_error("获取分类属性失败：无法找到分类。[{$category_id}]。");
            return FALSE;
        }
        /* 获取分类结束 */

        /* 获取属性模版开始 */
        $where = array(
            'attr_group_id' => $category['attr_group_id'],
            'is_delete'     => UNDELETED,
        );
        if($enable === TRUE)
        {
            $where['status'] = ATTR_GROUP_STATUS_ON;
        };

        $this->load->dao('Attr_group_dao');
        $attr_group = $this->Attr_group_dao->get_one($where);
        if( ! $attr_group)
        {
            $this->set_error("获取分类属性失败：无法找到属性模版。[{$category_id}]。");
            return FALSE;
        }
        /* 获取属性模版结束 */

        /* 获取属性开始 */
        $where = array(
            'attr_group_id' => $attr_group['attr_group_id'],
            'is_delete'     => UNDELETED,
        );
        if($enable === TRUE)
        {
            $where['status'] = ATTR_STATUS_ON;
        };
        $this->load->dao('Attr_dao');
        $attr = $this->Attr_dao->get(
            $where,
            array(
                'attr_id','name','sort','status'
            )
        );
        /* 获取属性结束 */
        
        if( $with_attr_value === TRUE)
        {
            $where = array(
                'attr_id'   => $attr['attr_id'],
                'is_delete' => UNDELETED,
            );
            if($enable === TRUE)
            {
                $where['status'] = ATTR_VALUE_STATUS_ON;
            };

            $attr_value_ids = array_pick($attr, 'attr_id', TRUE);

            $where = array(
                'is_delete' => UNDELETED,
            );
            if($enable === TRUE)
            {
                $where['status'] = ATTR_VALUE_STATUS_ON;
            };

            $this->load->dao('Attr_value_dao');
            $attr_values = $this->Attr_value_dao->get_in(
                array('attr_id'=>$attr_value_ids), 
                $where, 
                array(
                    'attr_id','attr_value_id','name','sort','status'
                ), 
                '`attr_id` ASC, `sort` ASC, `attr_value_id` ASC'
            );

            array_change_key($attr, 'attr_id');
            foreach ($attr_values as $av) 
            {
                $attr_id = $av['attr_id'];
                if( isset($attr[$attr_id]) )
                {
                    $attr[$attr_id]['children'][] = $av;
                }
            }
        }
        return $attr;
    }

    /**
     * [获得一个属性]
     * @param  [string]     $id
     * @param  [bool]       $enable        [是否排除"关闭状态"]
     * @param  [bool]       $with_attr     [是否包含属性值的信息]
     * @return [array/false]
     */
    public function get_attr($id, $enable = TRUE, $with_attr = FALSE)
    {
        if( ! validate($id, 'ATTR_ID') )
        {
            $this->set_error("获取属性失败：ID不正确。[{$id}]");
            return FALSE;
        }
        
        $where = array(
            'attr_id'   => $id,
            'is_delete' => UNDELETED,
        );
        if($enable === TRUE)
        {
            $where['status'] = ATTR_STATUS_ON;
        }

        $this->load->dao('Attr_dao');
        $attr = $this->Attr_dao->get_one(
            $where,
            array(
                'attr_id','attr_group_id','name','sort','status'
            )
        );
        if( ! $attr)
        {
            $this->set_error("获取属性失败：无法找到属性。[{$id}]。");
            return FALSE;
        }

        if( $with_attr === TRUE )
        {
            $where = array(            
                'attr_id'   => $id,
                'is_delete' => UNDELETED,
            );
            if($enable === TRUE)
            {
                $where['status'] = ATTR_VALUE_STATUS_ON;
            };

            $this->load->dao('Attr_value_dao');
            $attr['children'] = $this->Attr_value_dao->get(
                $where, 
                array(
                    'attr_id','attr_value_id','name','sort','status'
                ), 
                '`attr_id` ASC, `sort` ASC, `attr_value_id` ASC'
            );
        }
        return $attr;
    }

    /**
     * [获得一个属性值]
     * @param  [string]     $id
     * @param  [bool]       $enable        [是否排除"关闭状态"]
     * @return [array/false]
     */
    public function get_attr_value($id, $enable = TRUE)
    {
        if( ! validate($id, 'ATTR_ID') )
        {
            $this->set_error("获取属性值失败：ID不正确。[{$id}]");
            return FALSE;
        }
        
        $where = array(
            'attr_value_id'   => $id,
            'is_delete' => UNDELETED,
        );
        if($enable === TRUE)
        {
            $where['status'] = ATTR_VALUE_STATUS_ON;
        }

        $this->load->dao('Attr_value_dao');
        $attr = $this->Attr_value_dao->get_one(
            $where,
            array(
                'attr_id','name','sort','status'
            )
        );
        if( ! $attr)
        {
            $this->set_error("获取属性值失败：无法找到属性。[{$id}]。");
            return FALSE;
        }

        return $attr;
    }

    // --------------------------------------------------------------------
        
    /**
     * [改变一个属性的状态]
     * 
     * @param  [int]    $id     [编码]
     * @param  [string] $act    [操作类型]
     * @return [bool]
     */
    public function change_attr_status($id, $act)
    {   
        if( ! $attr = $this->get_attr($id, FALSE))
        {
            $this->set_error("修改属性状态失败：无法找到属性。[{$id}]");
            return FALSE;
        }

        // 初始化数据
        $_status       = NULL;  //修改的状态
        $_allow_status = NULL;  //允许修改的状态
        $_update       = NULL;  //更新的数据
        
        switch (strtolower(trim($act)))
        {
            case 'on':
                    $_status       = ATTR_STATUS_ON;
                    $_allow_status = array(ATTR_STATUS_OFF);
                    $_update       = array(
                        'status'       => $_status,
                        'update_time'  => now_str(),
                        'update_admin' => login_info('admin_id'), 
                    );
                break;

            case 'off':
                    $_status       = ATTR_STATUS_OFF;
                    $_allow_status = array(ATTR_STATUS_ON);
                    $_update       = array(
                        'status'       => $_status,
                        'update_time'  => now_str(),
                        'update_admin' => login_info('admin_id'), 
                    );
                break;

            default:
                    $this->set_error("修改属性状态失败：未知的操作[{$act}]。");
                    return FALSE;
                break;
        }

        $status      = $this->config->item('attr_status');
        $status_name = (string)$status[$_status];

        // 验证状态
        $current_status = (int)$attr['status'];
        if($current_status === $_status)
        {
            $this->set_error("修改属性状态失败：无需修改。");
            return FALSE;
        }

        if( $_allow_status && ! in_array($current_status, $_allow_status))
        {
            $this->set_error("修改属性状态失败：不允许被修改为[{$status_name}]状态。");
            return FALSE;
        }

       
        // 只有符合条件才会被修改
        $this->load->dao('Attr_dao');
        $affected_row = $this->Attr_dao->update_in(
            $_update,
            array('status'  => $_allow_status),
            array('attr_id' => $id)
        );
        if($affected_row<=0)
        {
            $this->set_error("修改属性状态失败：无法写入数据库。");
            return FALSE;
        }

        return TRUE;
    }

    /**
     * [改变一个属性值的状态]
     * 
     * @param  [int]    $id     [编码]
     * @param  [string] $act    [操作类型]
     * @return [bool]
     */
    public function change_attr_value_status($id, $act)
    {   
        if( ! $attr_value = $this->get_attr_value($id, FALSE))
        {
            $this->set_error("修改属性值状态失败：无法找到属性。[{$id}]");
            return FALSE;
        }

        // 初始化数据
        $_status       = NULL;  //修改的状态
        $_allow_status = NULL;  //允许修改的状态
        $_update       = NULL;  //更新的数据
        
        switch (strtolower(trim($act)))
        {
            case 'on':
                    $_status       = ATTR_VALUE_STATUS_ON;
                    $_allow_status = array(ATTR_VALUE_STATUS_OFF);
                    $_update       = array(
                        'status'       => $_status,
                        'update_time'  => now_str(),
                        'update_admin' => login_info('admin_id'), 
                    );
                break;

            case 'off':
                    $_status       = ATTR_VALUE_STATUS_OFF;
                    $_allow_status = array(ATTR_VALUE_STATUS_ON);
                    $_update       = array(
                        'status'       => $_status,
                        'update_time'  => now_str(),
                        'update_admin' => login_info('admin_id'), 
                    );
                break;

            default:
                    $this->set_error("修改属性值状态失败：未知的操作[{$act}]。");
                    return FALSE;
                break;
        }

        $status      = $this->config->item('attr_value_status');
        $status_name = (string)$status[$_status];

        // 验证状态
        $current_status = (int)$attr_value['status'];
        if($current_status === $_status)
        {
            $this->set_error("修改属性值状态失败：无需修改。");
            return FALSE;
        }

        if( $_allow_status && ! in_array($current_status, $_allow_status))
        {
            $this->set_error("修改属性值状态失败：不允许被修改为[{$status_name}]状态。");
            return FALSE;
        }

       
        // 只有符合条件才会被修改
        $this->load->dao('Attr_value_dao');
        $affected_row = $this->Attr_value_dao->update_in(
            $_update,
            array('status'        => $_allow_status),
            array('attr_value_id' => $id)
        );
        if($affected_row<=0)
        {
            $this->set_error("修改属性值状态失败：无法写入数据库。");
            return FALSE;
        }

        return TRUE;
    }


    /**
     * [改变一个属性模版的状态]
     * 
     * @param  [int]    $id     [编码]
     * @param  [string] $act    [操作类型]
     * @return [bool]
     */
    public function change_attr_group_status($id, $act)
    {   
        if( ! $attr_group = $this->get_attr_group($id, FALSE))
        {
            $this->set_error("修改属性模版状态失败：无法找到属性模版。[{$id}]");
            return FALSE;
        }

        // 初始化数据
        $_status       = NULL;  //修改的状态
        $_allow_status = NULL;  //允许修改的状态
        $_update       = NULL;  //更新的数据
        
        switch (strtolower(trim($act)))
        {
            case 'on':
                    $_status       = ATTR_GROUP_STATUS_ON;
                    $_allow_status = array(ATTR_GROUP_STATUS_OFF);
                    $_update       = array(
                        'status'       => $_status,
                        'update_time'  => now_str(),
                        'update_admin' => login_info('admin_id'), 
                    );
                break;

            case 'off':
                    $_status       = ATTR_GROUP_STATUS_OFF;
                    $_allow_status = array(ATTR_GROUP_STATUS_ON);
                    $_update       = array(
                        'status'       => $_status,
                        'update_time'  => now_str(),
                        'update_admin' => login_info('admin_id'), 
                    );
                break;

            default:
                    $this->set_error("修改属性模版状态失败：未知的操作[{$act}]。");
                    return FALSE;
                break;
        }

        $status      = $this->config->item('attr_group_status');
        $status_name = (string)$status[$_status];

        // 验证状态
        $current_status = (int)$attr_group['status'];
        if($current_status === $_status)
        {
            $this->set_error("修改属性模版状态失败：无需修改。");
            return FALSE;
        }

        if( $_allow_status && ! in_array($current_status, $_allow_status))
        {
            $this->set_error("修改属性模版状态失败：不允许被修改为[{$status_name}]状态。");
            return FALSE;
        }

       
        // 只有符合条件才会被修改
        $this->load->dao('Attr_group_dao');
        $affected_row = $this->Attr_group_dao->update_in(
            $_update,
            array('status'        => $_allow_status),
            array('attr_group_id' => $id)
        );
        if($affected_row<=0)
        {
            $this->set_error("修改属性模版状态失败：无法写入数据库。");
            return FALSE;
        }

        return TRUE;
    }

    // --------------------------------------------------------------------
    /**
     * [编辑属性]
     * @param   [array]       $params
     * @return  [int/false]
     */
    public function edit_attr($id, $params)
    {
        if( ! $attr = $this->get_attr($id, TRUE))
        {
            $this->set_error("修改属性失败：无法找到属性。[{$id}]");
            return FALSE;
        }

        $params = array(
            'name' => xss_clean(trim($params['name'])),
        );

        $data = array();

        if( isset($params['name']) )
        {
            /* 校验名称开始 */
            if( ! $this->val_attr_name($params['name']) )
            {
                return FALSE;
            }
            // 同一组方案下有没有同名
            $this->load->dao('Attr_dao');
            $count = $this->Attr_dao->count(array(
                'attr_group_id' => $attr['attr_group_id'],
                'is_delete'     => UNDELETED,
                'name'          => $params['name'],   
            ));
            if( $count > 0 )
            {
                $this->set_error("编辑属性失败：属性名称已经存在。[{$params['name']}]");
                return FALSE;
            }

            $data['name'] = $params['name'];
            /* 校验名称结束 */
        }
        
        if( ! $data )
        {
            $this->set_error("编辑属性失败：没有需要编辑的内容。");
            return FALSE;
        }

        // 编辑
        $data['update_admin'] = login_info('admin_id');
        $data['update_time']  = now_str();

        $where['attr_id']   = $id; 
        $where['status']    = ATTR_STATUS_ON; 
        $where['is_delete'] = UNDELETED;

        $this->load->dao('Attr_dao');
        $count = $this->Attr_dao->update(
            $data,
            $where,
            NULL,
            1
        );
        if( ! ($count > 0) )
        {
            $this->set_error("编辑属性失败：无法写入数据库。");
            return FALSE;
        }

        return TRUE;
    }

    /**
     * [编辑属性值]
     * @param   [array]       $params
     * @return  [int/false]
     */
    public function edit_attr_value($id, $params)
    {
        if( ! $attr_value = $this->get_attr_value($id, TRUE))
        {
            $this->set_error("修改属性值失败：无法找到属性值。[{$id}]");
            return FALSE;
        }

        $params = array(
            'name' => xss_clean(trim($params['name'])),
        );

        $data = array();

        if( isset($params['name']) )
        {
            /* 校验名称开始 */
            if( ! $this->val_attr_name($params['name']) )
            {
                return FALSE;
            }

            // 同一组属性下有没有同名
            $this->load->dao('Attr_value_dao');
            $count = $this->Attr_value_dao->count(array(
                'attr_id'   => $attr_value['attr_id'],
                'is_delete' => UNDELETED,
                'name'      => $params['name'],   
            ));
            if( $count > 0 )
            {
                $this->set_error("编辑属性值失败：属性值名称已经存在。[{$params['name']}]");
                return FALSE;
            }
            $data['name'] = $params['name'];
            /* 校验名称结束 */
        }
        
        if( ! $data )
        {
            $this->set_error("编辑属性值失败：没有需要编辑的内容。");
            return FALSE;
        }

        // 编辑
        $data['update_admin'] = login_info('admin_id');
        $data['update_time']  = now_str();

        $where['attr_value_id'] = $id; 
        $where['status']        = ATTR_VALUE_STATUS_ON; 
        $where['is_delete']     = UNDELETED;

        $this->load->dao('Attr_value_dao');
        $count = $this->Attr_value_dao->update(
            $data,
            $where,
            NULL,
            1
        );
        if( ! ($count > 0) )
        {
            $this->set_error("编辑属性值失败：无法写入数据库。");
            return FALSE;
        }

        return TRUE;
    }

    /**
     * [批量编辑属性排序]
     * @param  [array] $params [array(0=>array('id'=>1)...)]
     * @return [bool]
     */
    public function edit_attr_sort_batch($params)
    {
        if( ! is_array($params) || ! $params)
        {
            $this->set_error("批量编辑属性排序失败：请提供正确的参数。");
            return FALSE;
        }

        $data = array();
        $sort = 1;

        $update_time  = now_str();
        $update_admin = login_info('admin_id');
        foreach($params as $p)
        {
            if( ! validate($p['id'], 'ATTR_ID') )
            {
                continue;
            }
            $data[] = array(
                'attr_id'      => $p['id'],
                'sort'         => $sort,
                'update_time'  => & $update_time,
                'update_admin' => & $update_admin,
            );
            $sort++;
        }

        $this->load->dao('Attr_dao');
        $this->Attr_dao->update_batch($data, 'attr_id');

        return TRUE;   
    }

    /**
     * [批量编辑属性值排序]
     * @param  [array] $params [array(0=>array('id'=>1)...)]
     * @return [bool]
     */
    public function edit_attr_value_sort_batch($params)
    {
        if( ! is_array($params) || ! $params)
        {
            $this->set_error("批量编辑属性值排序失败：请提供正确的参数。");
            return FALSE;
        }

        $data = array();
        $sort = 1;

        $update_time  = now_str();
        $update_admin = login_info('admin_id');
        foreach($params as $p)
        {
            if( ! validate($p['id'], 'ATTR_VALUE_ID') )
            {
                continue;
            }
            $data[] = array(
                'attr_value_id'=> $p['id'],
                'sort'         => $sort,
                'update_time'  => & $update_time,
                'update_admin' => & $update_admin,
            );
            $sort++;
        }

        $this->load->dao('Attr_value_dao');
        $this->Attr_value_dao->update_batch($data, 'attr_value_id');

        return TRUE;   
    }

    // --------------------------------------------------------------------

    /**
     * [删除一个属性]
     * @param  [int]    $id   
     * @return [bool]
     */
    public function del_attr($id)
    {
        if( ! validate($id, 'ATTR_ID') )
        {
            $this->set_error("删除属性失败：属性ID不正确。[{$id}]");
            return FALSE;
        }

        // 如果有商品还在使用这个属性，无法删除
        $this->load->dao('Goods_attr_dao');
        $count = $this->Goods_attr_dao->count(array(
            'attr_id'   => $id,
            'is_delete' => UNDELETED,
        ));

        if( $count > 0 )
        {
            $this->set_error("删除属性失败：该属性正在被{$count}个商品使用，请先从这些商品中移除这个属性。");
            return FALSE;
        }

        // 删除属性
        $this->load->dao('Attr_dao');
        $this->Attr_dao->update(
            array(
                'is_delete'    => DELETED,
                'update_time'  => now_str(),
                'update_admin' => login_info('admin_id')
            ),
            array(
                'attr_id' => $id,
            )
        );

        // 删除属性值
        $this->load->dao('Attr_value_dao');
        $this->Attr_value_dao->update(
            array(
                'is_delete'    => DELETED,
                'update_time'  => now_str(),
                'update_admin' => login_info('admin_id')
            ),
            array(
                'attr_id' => $id,
            )
        );

        return TRUE;
    }

    /**
     * [删除一个属性值]
     * @param  [int]    $id   
     * @return [bool]
     */
    public function del_attr_value($id)
    {
        if( ! validate($id, 'ATTR_VALUE_ID') )
        {
            $this->set_error("删除属性值失败：属性值ID不正确。[{$id}]");
            return FALSE;
        }

        // 如果有商品还在使用这个属性，无法删除
        $this->load->dao('Goods_attr_dao');
        $count = $this->Goods_attr_dao->count(array(
            'attr_value_id' => $id,
            'is_delete'     => UNDELETED,
        ));

        if( $count > 0 )
        {
            $this->set_error("删除属性值失败：该属性值正在被{$count}个商品使用，请先从这些商品中移除这个属性值。");
            return FALSE;
        }

        // 删除属性值
        $this->load->dao('Attr_value_dao');
        $this->Attr_value_dao->update(
            array(
                'is_delete'    => DELETED,
                'update_time'  => now_str(),
                'update_admin' => login_info('admin_id')
            ),
            array(
                'attr_value_id' => $id,
            )
        );

        return TRUE;
    }
}